package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.service.RecipeService;
import com.recipedb.recipedb.util.MergeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.recipedb.recipedb.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.recipedb.recipedb.util.MergeUtils.mergeForPut;

@RestController
@RequestMapping("/api/recipe")
public class RecipeController {

    @Autowired
    private RecipeService service;

    @Autowired
    private UserService userService; // 新增注入：用于解析登录用户ID

    @PostMapping
    public Recipe add(@RequestBody Recipe entity) {
        return service.save(entity);
    }

    @DeleteMapping
    public void delete(@RequestParam Long id) {
        service.deleteById(id);
    }

    @GetMapping("/single")
    public Optional<Recipe> get(@RequestParam Long id) {
        return service.findById(id);
    }

    @GetMapping("/all")
    public List<Recipe> getAll() {
        return service.findAll();
    }

    @GetMapping("/search")
    public List<Recipe> search(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String ingredient) {
        return service.search(keyword, tag, category, ingredient);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Recipe>> getRecipesByUserId(@PathVariable Long userId) {
        List<Recipe> recipes = service.findByUserId(userId);
        if (recipes.isEmpty()) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(recipes);
    }

    @PatchMapping("/{id}")
    public ResponseEntity<Recipe> partialUpdate(@PathVariable Long id, @RequestBody Recipe entity) {
        Optional<Recipe> updatedRecipe = service.partialUpdate(id, entity);
        return updatedRecipe
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Recipe> update(
            @PathVariable Long id,
            @RequestBody Recipe incoming) {

        Optional<Recipe> existingOpt = service.findById(id);
        if (existingOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        Recipe merged = MergeUtils.mergeForPut(existingOpt.get(), incoming);

        Optional<Recipe> updated = service.partialUpdate(id, merged);
        return updated
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }


    // 获取单个食谱的被收藏数
    @GetMapping("/{recipeId}/favorite-count")
    public ResponseEntity<Long> getRecipeFavoriteCount(@PathVariable Long recipeId) {
        Long count = service.getFavoriteCountByRecipeId(recipeId);
        return ResponseEntity.ok(count);
    }

    @PostMapping("/refresh-changed-favorite-counts")
    public ResponseEntity<Map<Long, Long>> refreshChangedFavoriteCounts() {
        Map<Long, Long> changedCounts = service.refreshAndGetChangedFavoriteCounts();
        return ResponseEntity.ok(changedCounts);
    }

    // ========== 新增：我的发布搜索接口 ==========
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<Page<Recipe>> searchUserRecipes(
            @PathVariable Long userId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String ingredient,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication) {

        // 1. 权限校验：仅允许查询当前登录用户的发布
        Long currentUserId = userService.getUserIdByUsername(authentication.getName());
        if (!currentUserId.equals(userId)) {
            throw new AccessDeniedException("无权查询他人的发布食谱");
        }

        // 2. 调用Service获取分页结果
        Page<Recipe> result = service.searchUserRecipes(
                userId,
                keyword,
                tag,
                category,
                ingredient,
                pageNum,
                pageSize
        );

        // 3. 返回结果（空列表也返回200，前端处理）
        return ResponseEntity.ok(result);
    }
    @PostMapping("/cover/{recipeId}")
    public ResponseEntity<String> uploadCover(
            @PathVariable Long recipeId,
            @RequestParam("file") MultipartFile file) throws IOException {

        // 查找食谱
        Recipe recipe = service.findById(recipeId).orElse(null);
        if (recipe == null) return ResponseEntity.notFound().build();

        // 保存文件
        String fileName = String.format("R%06d.jpg", recipeId);
        String dir = "/var/www/recipe-app/uploads/recipes/cover/";
        File targetDir = new File(dir);
        if (!targetDir.exists()) targetDir.mkdirs();

        File targetFile = new File(targetDir, fileName);
        file.transferTo(targetFile);

        // 更新数据库封面路径
        String dbPath = "/uploads/recipes/cover/" + fileName;
        recipe.setCoverImage(dbPath);
        service.partialUpdate(recipeId, recipe);

        return ResponseEntity.ok(dbPath);
    }

}